class Solution {
public:
    int tmp[1000001];
    int tmpindex[1000001];
    vector<int> ret;
    vector<int> index;

    vector<int> countSmaller(vector<int>& nums) {
        int n = nums.size();
        ret.resize(n);
        index.resize(n);
        for (int i = 0; i < n; i++)
            index[i] = i;
        MergeSort(nums, 0, n - 1);
        return ret;
    }

    void MergeSort(vector<int>& nums, int left, int right)
    {
        if (left >= right) return;

        int mid = left + (right - left) / 2;
        MergeSort(nums, left, mid);
        MergeSort(nums, mid + 1, right);

        int cur1 = left, cur2 = mid + 1, i = 0;
        while (cur1 <= mid && cur2 <= right)
        {
            if (nums[cur1] <= nums[cur2]) {
                tmp[i] = nums[cur2];
                tmpindex[i++] = index[cur2++];
            }
            else {
                ret[index[cur1]] += right - cur2 + 1;
                tmp[i] = nums[cur1];
                tmpindex[i++] = index[cur1++];
            }
        }
        while (cur1 <= mid) {
            tmp[i] = nums[cur1];
            tmpindex[i++] = index[cur1++];
        }
        while (cur2 <= right) {
            tmp[i] = nums[cur2];
            tmpindex[i++] = index[cur2++];
        }

        for (int k = left; k <= right; k++)
        {
            nums[k] = tmp[k - left];
            index[k] = tmpindex[k - left];
        }
    }
};